﻿using System.Collections.Generic;
using System.Linq;

namespace Newbe.TestDirector.Notification.Web.Domain.Impl
{
    internal class TestDirectorAccessDbComparer : ITestDirectorAccessDbComparer
    {
        BugChangeResultCollection ITestDirectorAccessDbComparer.Compare(IEnumerable<BugData> old,
            IEnumerable<BugData> now)
        {
            var oldData = old.ToDictionary(x => x.Id);
            var nowData = now;
            var bugChangeResults = nowData.AsParallel().Select(nowDataRow =>
            {
                if (oldData.ContainsKey(nowDataRow.Id))
                {
                    var oldRow = oldData[nowDataRow.Id];
                    var oldRowFieldDic = oldRow.Fields.ToDictionary(x => x.TableColumn);
                    var r = new BugChangeResult(nowDataRow)
                    {
                        Id = nowDataRow.Id,
                        ChangedFields = new BugChangeFieldTableCollection(nowDataRow.Fields
                            .Where(x => oldRowFieldDic[x.TableColumn].Value != x.Value)
                            .Select(
                                x => new BugChangeFieldResult
                                {
                                    TableColumn = x.TableColumn,
                                    NowValue = x.Value,
                                    OldValue = oldRowFieldDic[x.TableColumn].Value
                                }).ToArray())
                    };
                    return r;
                }
                return new BugChangeResult(nowDataRow)
                {
                    Id = nowDataRow.Id,
                    ChangedFields = new BugChangeFieldTableCollection(nowDataRow.Fields.Select(a =>
                        new BugChangeFieldResult
                        {
                            TableColumn = a.TableColumn,
                            OldValue = string.Empty,
                            NowValue = a.Value
                        }).ToArray())
                };
            }).Where(x => x.HasChanged).ToArray();
            return new BugChangeResultCollection(bugChangeResults);
        }
    }
}
